package pkg.chemdrm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.PriorityQueue;

import org.anddev.andengine.entity.sprite.Sprite;

public class ElementMoleculeDB {
	
	HashMap<Integer, Substance> mDb; 
	
	/*
	public Sprite getSpriteForSubstanceID(int id)
	{
		if(mDb.containsKey(id))
			return mDb.get(id);
		
		return null; // return null if there is no substance with that id
		
	}
	*/
	
	public ElementMoleculeDB()
	{
		mDb = new HashMap<Integer, Substance>();
		
		// Hydrogen (H)
		mDb.put(0, new Substance("Hydrogen", "H", 0, true));
		// Carbon (C)
		mDb.put(1, new Substance("Carbon", "C", 1, true));
		// Nitrogen (N)
		mDb.put(2, new Substance("Nitrogen", "N", 2, true));
		// Oxygen (O)
		mDb.put(3, new Substance("Oxygen", "O", 3, true));
		// Sodium (Na)
		mDb.put(4, new Substance("Sodium", "Na", 4, true));
		// Chlorine (Cl)
		mDb.put(5, new Substance("Chlorine", "Cl", 5, true));
		
		// salt
		// NaCl
		mDb.put(6, new Substance("Salt", "NaCl", 6, false));
		
		// Caffeine
		// HCN
		mDb.put(7, new Substance("Caffeine", "HCN", 7, true));
		
		// Water
		// HO
		mDb.put(8, new Substance("Water", "HO", 8, true));
		
		
		
	}
	
	public Substance getSubstance(final String pName)
	{
		int id = getIdFromSubstanceName(pName);
		if (id != -1)
		{
			return mDb.get(id);
		}
		
		return null;
	}
	
	// pass an id, look up the elemnet name
	public Substance getSubstanceFromID(final int id)
	{
		if(mDb.containsKey(id))
			return mDb.get(id);
		
		return null; // return null if there is no substance with that id
		
	}
	
	// return an integer when given a string name
	public Integer getIdFromSubstanceName(final String pName)
	{
		for(Substance s : mDb.values())
		{
			if(s.mName.equals(pName))
				return s.mId;
			
		}
		
		return -1 ; // notfound!
	}
	
	public Integer getIdFromSubstanceSymbol(final String pName)
	{
		for(Substance s : mDb.values())
		{
			if(s.mSymbol.equals(pName))
				return s.mId;
			
		}
		
		return -1 ; // notfound!
	}
	
	// TODO: Add a parameter to this method that allows you to check if the list of things you have is an actual combination or not
	public Substance combine(ArrayList<Substance> pSubstances)
	{
		PriorityQueue<Integer> sortedIds = new PriorityQueue<Integer>();
		StringBuffer molecule = new StringBuffer();
		// sort pSubstances by uid; we do this by throwing them in a PQ
		for(Substance s : pSubstances)
		{
			sortedIds.add(s.mId);
		}
		
		// combine in to a single string using StringBuffer
		for(Integer i : sortedIds)		
		{
			molecule.append(getSubstanceFromID(i).mSymbol);
		}
		
		System.err.println("New Molecule: " + molecule.toString());
		// check StringBuffer result against db
		int id = getIdFromSubstanceSymbol(molecule.toString()); 
		
		if(id != -1)
			return mDb.get(id);
		
		
		return null; // return null if it isn't a combination
	}
	
	
}
